package com.cyq.blog.intercepter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyq.blog.entity.Blog;
import com.cyq.blog.service.BlogService;
import com.cyq.blog.util.MybatisPlusUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;

/**
 * RedisUrlIntercepter class
 * 记录 博客页的访问量
 * @author chenyeqing
 * @date 2021/5/20
 */
@Slf4j
@Component
public class RedisUrlIntercepter implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private BlogService blogService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info(RedisUrlIntercepter.class.getName() + "-URI=>" + request.getRequestURI());
        String requestURL = request.getRequestURI();
        String urlOrId = requestURL.split("/")[2];

        // 查询条件
        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();
        blogQueryWrapper.eq("blog_custom_url", urlOrId);
        blogQueryWrapper.eq("blog_status", 1);
        blogQueryWrapper.eq("is_deleted", 0);
        // 先根据 自定义url 找
        Blog showBlog;
        List<Blog> list = blogService.list(blogQueryWrapper);
        if (list.size() >= 1) {
            // 重复就显示查到的第一条  懒得写查到阅读量最高了
            showBlog = list.get(0);
        } else {
            // 如果没有则根据 ID
            showBlog = blogService.getById(urlOrId);
        }
        Assert.notNull(showBlog, "找不到");
        // 从缓存中读取当前博客的阅读量，没有则从数据库中查询
        if (!StringUtils.hasText(stringRedisTemplate.opsForValue().get(requestURL))) {
            stringRedisTemplate.opsForValue().set(requestURL, String.valueOf(showBlog.getBlogViews()));
        }
        // 每次访问+1
        stringRedisTemplate.opsForValue().increment(requestURL);
        return true;
    }
}
